package com.zzr.demo.redis.service.impl;

import com.zzr.demo.redis.service.CounterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;

import java.util.concurrent.TimeUnit;

/**
 * @author: xiaomi
 * @date: 2021/10/8
 * @description: 单一限速器.
 * 限定时间内，多执行次数进行限制。
 */
@Service("SpeedLimiter")
@Slf4j
public class SpeedLimiterServiceImpl implements CounterService {


    final String SPEED_LIMITER_KEY_NAME = "speed::limiter";
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    /**
     * 默认限速器的时间为1 分钟
     *
     * @param value
     * @return
     */
    @Override
    public boolean init(int value) {
        stringRedisTemplate.opsForValue().set(SPEED_LIMITER_KEY_NAME, value + "", 1, TimeUnit.MINUTES);
        return true;
    }

    @Override
    public long increase() {
        throw new NotImplementedException();
    }

    @Override
    public long increase(int num) {
        throw new NotImplementedException();
    }

    @Override
    public long decrease() {
        initIfAbsent();
        Long decrement = stringRedisTemplate.opsForValue().decrement(SPEED_LIMITER_KEY_NAME);
        return decrement;
    }

    @Override
    public long decrease(int num) {
        initIfAbsent();
        Long decrement = stringRedisTemplate.opsForValue().decrement(SPEED_LIMITER_KEY_NAME, num);
        return decrement;
    }

    /**
     * 如果key 不存在，就进行初始化
     */
    void initIfAbsent() {
        String str = stringRedisTemplate.opsForValue().get(SPEED_LIMITER_KEY_NAME);
        if (str == null) {
            //如果 key 已经过期了，那么进行初始化，默认 5
            init(5);
        }
    }
}
